package com.xmut.bs.handaccount.activity;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.snappingstepper.SnappingStepper;
import com.bigkoo.snappingstepper.listener.SnappingStepperValueChangeListener;
import com.xmut.bs.handaccount.GlideApp;
import com.xmut.bs.handaccount.R;
import com.xmut.bs.handaccount.adapter.GoodsDetailAdapter;
import com.xmut.bs.handaccount.base.ToolbarBaseActivity;
import com.xmut.bs.handaccount.bean.GoodsDetail;
import com.xmut.bs.handaccount.bmob.Comment;
import com.xmut.bs.handaccount.bmob.Goods;
import com.xmut.bs.handaccount.bmob.Order;
import com.xmut.bs.handaccount.bmob.User;
import com.xmut.bs.handaccount.util.StringUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;

import static com.xmut.bs.handaccount.base.Constants.ORDER_WAIT;
import static com.xmut.bs.handaccount.base.Constants.PARAM_GOODS;
import static com.xmut.bs.handaccount.util.StringUtil.calculation2Decimal;

/**
 * Description
 * Created by Dollkey on 2018/4/11.
 */

public class GoodsDetailActivity extends ToolbarBaseActivity {

    @BindView(R.id.goods_img)
    ImageView mGoodsImg;
    @BindView(R.id.goods_price)
    TextView mGoodsPrice;
    @BindView(R.id.goods_name)
    TextView mGoodsName;
    @BindView(R.id.goods_note)
    TextView mGoodsNote;
    @BindView(R.id.tv_note_content)
    RecyclerView mTvNoteContent;
    private Goods mGoods;
    private BottomSheetDialog dialog;
    private SnappingStepper stepper;
    private ProgressDialog insertDialog;
    private TextView mPriceTv;
    private User mUser;
    private GoodsDetailAdapter mAdapter;
    private List<GoodsDetail> mList;
    private android.support.v7.app.AlertDialog successDialog;

    @Override
    protected String getSubTitle() {
        return "商品详情";
    }

    @Override
    protected int bindLayoutId() {
        return R.layout.activity_goods_detail;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mList = new ArrayList<>();
        mUser = BmobUser.getCurrentUser(User.class);
        insertDialog = new ProgressDialog(this);
        insertDialog.setMessage("正在下单...");
        mGoodsPrice.setText("￥".concat(String.valueOf(mGoods.getPrice())));
        mGoodsName.setText(mGoods.getName());
        mGoodsNote.setText(mGoods.getDescription());
        GlideApp.with(mGoodsImg).load(mGoods.getBannerUrls().get(0)).fitCenter().into(mGoodsImg);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setSmoothScrollbarEnabled(true);
        layoutManager.setAutoMeasureEnabled(true);
        mTvNoteContent.setLayoutManager(layoutManager);
        mTvNoteContent.setHasFixedSize(true);
        mTvNoteContent.setNestedScrollingEnabled(false);
        mTvNoteContent.setItemAnimator(new DefaultItemAnimator());
        int size = mGoods.getDetailUrls().size();
        mList.add(new GoodsDetail(3));
        for (int i = 0; i < size; i++) {
            mList.add(new GoodsDetail(mGoods.getDetailUrls().get(i)));
        }
        mAdapter = new GoodsDetailAdapter(mContext, mList, mGoods);
        mTvNoteContent.setAdapter(mAdapter);
        queryComment();
    }

    private void queryComment() {
        BmobQuery<Comment> query = new BmobQuery<>();
        query.addWhereEqualTo("goods", mGoods);
        query.addWhereEqualTo("article", null);
        query.order("-updatedAt");
        query.setLimit(2);
        query.include("user");// 希望在查询帖子信息的同时也把发布人的信息查询出来
        query.findObjects(new FindListener<Comment>() {
            @Override
            public void done(List<Comment> list, BmobException e) {
                if (e == null) {
                    if (list.size() > 0) {
                        for (Comment comment : list) {
                            mList.add(0, new GoodsDetail(comment));
                        }
                        mList.add(0, new GoodsDetail());
                        mAdapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }

    @Override
    protected void initParams(Intent intent) {
        mGoods = (Goods) intent.getSerializableExtra(PARAM_GOODS);
    }

    @OnClick(R.id.buy_btn)
    public void onViewClicked() {
        if (mUser == null) {
            showToast("请先登录");
            return;
        }
        showDialog();
    }

    public void showDialog() {
        if (dialog == null) {
            dialog = new BottomSheetDialog(mContext);
            View dialogView = LayoutInflater.from(mContext).inflate(R.layout.pop_order_count, null);
            stepper = dialogView.findViewById(R.id.stepper);
            stepper.setMinValue(1);
            mPriceTv = dialogView.findViewById(R.id.price_tv);
            Button buyBtn = dialogView.findViewById(R.id.commit_buy_btn);
            buyBtn.setBackgroundColor(colorPrimary);
            buyBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    insertDialog.show();
                    Order order = new Order();
                    order.setCount(stepper.getValue());
                    order.setGoods(mGoods);
                    order.setSubtotal(calculation2Decimal(mGoods.getPrice(), stepper.getValue()));
                    order.setUser(mUser);
                    order.setStatus(ORDER_WAIT);
                    order.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            insertDialog.dismiss();
                            if (e == null) {
                                showSuccessDialog();
                            } else {
                                showToast("失败：" + e.getMessage() + "," + e.getErrorCode());
                            }
                        }
                    });
                }
            });
            stepper.setOnValueChangeListener(new SnappingStepperValueChangeListener() {
                @Override
                public void onValueChange(View view, int value) {
                    mPriceTv.setText("￥".concat(calculation2Decimal(mGoods.getPrice(), value)));
                }
            });
            dialog.setContentView(dialogView);
        }
        stepper.setValue(1);
        mPriceTv.setText("￥".concat(StringUtil.notNull(String.valueOf(mGoods.getPrice()))));
        dialog.show();
    }

    private void showSuccessDialog() {
        if (successDialog != null) {
            successDialog.show();
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("下单成功");
        //监听下方button点击事件
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                finish();
            }
        });
        builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });
        builder.setCancelable(false);
        successDialog = builder.create();
        successDialog.show();
    }
}
